package org.springblade.modules.enterprise.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.enterprise.entity.VisitorCount;
import org.springblade.modules.enterprise.service.IVisitorCountService;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import java.time.LocalDate;

@Slf4j
@Component
@AllArgsConstructor
@WebListener
public class SessionListener implements ServletRequestListener {

	private IVisitorCountService visitorCountService;

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		ServletRequestListener.super.requestInitialized(sre);
		// 获取当天访问最新数据
		final VisitorCount visitorCountQueryWrapper = new VisitorCount();
		visitorCountQueryWrapper.setCurrDay(LocalDate.now());
		final VisitorCount visitorCount = visitorCountService.getOne(new QueryWrapper<>(visitorCountQueryWrapper));
		// 如果存在 count+1
		if (Func.isNotEmpty(visitorCount)) {
			// 更新
			visitorCount.setCount(visitorCount.getCount() + 1);
			visitorCountService.saveOrUpdate(visitorCount);
		} else {
			// 插入
			visitorCountQueryWrapper.setCount(1L);
			visitorCountService.saveOrUpdate(visitorCountQueryWrapper);
		}
	}
}
